package zxing.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import org.litepal.crud.DataSupport;

import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.virtualapp.R;
import io.virtualapp.abs.ui.VActivity;
import io.virtualapp.bean.MakeBean;
import io.virtualapp.bean.NumBean;
import io.virtualapp.bean.ResultBean;
import io.virtualapp.mylibrary.callback.BaseCallback;
import io.virtualapp.mylibrary.util.HttpUtils;
import io.virtualapp.mylibrary.util.PermissionUtils;
import io.virtualapp.mylibrary.util.ToastUtils;
import io.virtualapp.mylibrary.util.Utils;
import io.virtualapp.utils.ImageUtils;
import okhttp3.Request;
import okhttp3.Response;
import zxing.activity.bean.LoveBean;

public class LoveLetterActivity extends VActivity implements View.OnClickListener {
    String voiceFilePath, voiceName, voiceFileName;
    @BindView(R.id.head_back)
    ImageView head_back;
    @BindView(R.id.head_center_title)
    TextView head_center_title;
    @BindView(R.id.rela_music)
    RelativeLayout rela_music;
    @BindView(R.id.txt_Music)
    TextView txtMusic;
    @BindView(R.id.rela_back)
    RelativeLayout rela_back;
    @BindView(R.id.text_bg)
    TextView text_bg;
    @BindView(R.id.edit_theme)
    EditText edit_theme;
    @BindView(R.id.edit_content)
    EditText edit_content;
    @BindView(R.id.dateDisplay)
    TextView dateDisplay;
    @BindView(R.id.rela_time)
    RelativeLayout rela_time;
    @BindView(R.id.button_star)
    Button buttonStar;

    @BindView(R.id.edit_youname)
    EditText editYouname;
    @BindView(R.id.edit_heName)
    EditText editHeName;
    int pos = 0;
    int selectPos = 0;
    String imageFilePath, imageName;
    final int DATE_DIALOG = 1;
    int mYear, mMonth, mDay;
    String title, context, name1, name2;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_love_letter);
        ButterKnife.bind(this);
        head_center_title.setText("情书");
        rela_music.setOnClickListener(this);
        rela_back.setOnClickListener(this);
        rela_time.setOnClickListener(this);
        buttonStar.setOnClickListener(this);
        head_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        final Calendar ca = Calendar.getInstance();
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);
        getView();
    }

    public void getView() {
        edit_theme.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 255) {
                    Toast.makeText(LoveLetterActivity.this, "字数上限了，亲", Toast.LENGTH_SHORT).show();
                }
            }
        });
        edit_content.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() >= 2550) {
                    Toast.makeText(LoveLetterActivity.this, "字数上限了，亲", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rela_music:
                Intent intent = new Intent(getActivity(), MusicListActivity.class);
                intent.putExtra("pos", pos);
                startActivityForResult(intent, 1);
                break;
            case R.id.rela_back:
                Intent intent1 = new Intent(getActivity(), LoveBackgroundActivity.class);
                intent1.putExtra("pos", selectPos);
                startActivityForResult(intent1, 0);
                break;
            case R.id.rela_time:
                showDialog(DATE_DIALOG);
                break;
            case R.id.button_star:
                if (TextUtils.isEmpty(edit_theme.getText().toString())) {
                    Toast.makeText(LoveLetterActivity.this, "主题不能为空", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(edit_content.getText().toString())) {
                    Toast.makeText(LoveLetterActivity.this, "主题内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(imageFilePath)) {
                    Toast.makeText(LoveLetterActivity.this, "情书模板未选择", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(voiceFilePath)) {
                    Toast.makeText(LoveLetterActivity.this, "背景音乐未选择", Toast.LENGTH_SHORT).show();
                    return;
                }
                voiceFileName = voiceFilePath.replace("http://pay.wm002.cn/upload/music/", "");
                title = edit_theme.getText().toString();
                context = edit_content.getText().toString();
                name1 = editYouname.getText().toString();
                name2 = editHeName.getText().toString();
                UpLoadService();
                break;
            default:
                break;
        }
    }


    private void UpLoadService() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpUtils.getInstance().addLove(

                        title + "",
                        context + "",
                        name1 + "",
                        name2 + "",
                        imageFilePath + "",
                        voiceFileName + "",
                        new BaseCallback<LoveBean>() {
                            @Override
                            public void onRequestBefore() {
                            }

                            @Override
                            public void onFailure(Request request, Exception e) {
                                new Handler(getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtils.showShortToast("提交失败" + e.toString());
                                    }
                                });
                            }

                            @Override
                            public void onSuccess(Response response, LoveBean o) {
                                if (o != null && o.isIssucc()) {
                                    ToastUtils.showShortToast("提交成功");
                                    LoveLetterActivity.this.setResult(RESULT_OK);
                                    String url = o.getData() + "";
                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
                                    Date date = new Date(System.currentTimeMillis());
                                    String n = simpleDateFormat.format(date);
                                    MakeBean user = new MakeBean();
                                    user.setName(n);
                                    user.setTit(url + "");
                                    user.save();
                                    NumBean numBean = new NumBean();
                                    if (DataSupport.findFirst(NumBean.class) != null) {
                                        DataSupport.deleteAll(NumBean.class);
                                    }
                                    numBean.setNum(2);
                                    numBean.save();
                                    Intent intent = new Intent(getActivity(), CodeDisplayActivity.class);
                                    intent.putExtra("data", url);
                                    intent.putExtra("title", "情书二维码");
                                    startActivityForResult(intent, 2);
                                } else {
                                    new Handler(getMainLooper()).post(new Runnable() {
                                        @Override
                                        public void run() {
                                            ToastUtils.showShortToast("提交失败" + o.getMsg());
                                        }
                                    });
                                }

                            }

                            @Override
                            public void onError(Response response, int errorCode, Exception e) {
                                new Handler(getMainLooper()).post(new Runnable() {
                                    @Override
                                    public void run() {
                                        ToastUtils.showShortToast("提交失败" + e.toString());
                                    }
                                });
                            }
                        });

            }
        }).

                start();

    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
        }
        return null;
    }

    public void display() {
        dateDisplay.setText(new StringBuffer().append(mYear).append("-").append(mMonth + 1).append("-").append(mDay).append(" "));
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            display();
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0:
                if (data != null) {
                    imageFilePath = data.getStringExtra("imageFilePath");
                    imageName = data.getStringExtra("imageName");
                    selectPos = data.getIntExtra("selectPos", 0);
                    text_bg.setText(imageName + "");
                }
                break;

            case 1:
                if (data != null) {
                    voiceFilePath = data.getStringExtra("voiceFilePath");
                    voiceName = data.getStringExtra("voiceName");
                    pos = data.getIntExtra("pos", 0);
                    txtMusic.setText(voiceName);

                }
                break;
            case 2:
                voiceFileName = null;
                edit_theme.setText(null);
                edit_content.setText(null);
                editYouname.setText(null);
                editHeName.setText(null);
                title = null;
                context = null;
                name1 = null;
                name2 = null;
                imageFilePath = null;
                txtMusic.setText("选择背景音乐");
                text_bg.setText("选择情书模板");
                break;

            default:
                break;
        }
    }

}
